package bai.publicwelfare_backend.exception;

import bai.publicwelfare_backend.exception.BusinessException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.context.MessageSource;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;

// GlobalExceptionHandler.java
@RestControllerAdvice
@RequiredArgsConstructor
public class GlobalExceptionHandler {
    private final MessageSource messageSource;

    // 处理业务异常
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<ErrorResponse> handleBusinessException(
            BusinessException ex,
            HttpServletRequest request) {  // 移除了Locale参数

        // 直接使用异常中的消息（无需再通过MessageSource解析）
        ErrorResponse response = ErrorResponse.builder()
                .requestId(request.getHeader("X-Request-ID")) // 按需获取请求ID
                .status(ex.getErrorCode().getHttpStatus())
                .code(ex.getErrorCode().getCode())
                .message(ex.getMessage())  // 直接传递异常消息
                .build();

        return ResponseEntity
                .status(ex.getErrorCode().getHttpStatus())
                .body(response);
    }

    // 处理参数校验异常（完整可运行版本）
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ErrorResponse> handleValidationException(
            MethodArgumentNotValidException ex,
            HttpServletRequest request) {

        // 提取校验失败的字段和错误信息
        Map<String, String> details = ex.getBindingResult().getFieldErrors().stream()
                .collect(Collectors.toMap(
                        FieldError::getField, // 字段名作为key
                        DefaultMessageSourceResolvable::getDefaultMessage // 错误信息作为value
                ));

        ErrorResponse response = ErrorResponse.builder()
                .requestId(request.getHeader("X-Request-ID"))
                .status(400)
                .code("VALIDATION_FAILED") // 你可以定义在ErrorCode中
                .message("参数校验失败")
                .details(details) // 包含具体字段错误
                .build();

        return ResponseEntity.badRequest().body(response);
    }
}
